<template>
  <el-dialog :title="title"
             :visible.sync="visible"
             v-loading="loading"
             :before-close="modalClose"
             :close-on-click-modal="false"
             :close-on-press-escape="false"
             width="80%">
    <el-form ref="formRef"
             :model="formModel"
             :rules="formRules"
             label-width="130px">
      <el-form-item label="主题类型："
                    prop="type">
        <el-radio-group v-model="formModel.type">
          <el-radio-button :label="2">特色专项主题</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="活动名称："
                    prop="name">
        <el-input v-model="formModel.name"
                  placeholder="请输入活动名称"
                  class="w-200"></el-input>
      </el-form-item>
      <el-form-item label="活动主题："
                    prop="themeId">
        <el-select v-model="formModel.themeId"
                   :disabled="dataObj ? true : false"
                   placeholder="请选择活动主题"
                   filterable
                   remote
                   reserve-keyword
                   clearable
                   :remote-method="(query) => {remoteMethod(query, 'theme')}"
                   :loading="loading3"
                   class="w-500"
                   @change="val=>handleSelect(val, 'theme')">
          <el-option v-for="item in activeThemeFilterList"
                     :key="item.id"
                     :label="item.deviceNames"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 根据活动查询出合并症 -->
      <el-form-item label="关联病症："
                    prop="associate">
        <el-tag type="danger"
                v-for="item in tabConTitle"
                :key="item.id"
                style="margin-right:10px;">{{item.name}}</el-tag>
      </el-form-item>
      <el-form-item label="参与活动厂家："
                    prop="factoryIds">
        <el-select v-model="formModel.factoryIds"
                   placeholder="请选择参与活动厂家"
                   multiple
                   filterable
                   remote
                   reserve-keyword
                   clearable
                   :remote-method="(query) => {remoteMethod(query, 'factory')}"
                   :loading="loading2"
                   class="w-200"
                   @change="val=>handleSelect(val, 'factory')">
          <el-option v-for="item in activityFilterFactory"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="活动关联权益："
                    prop="inviolableId">
        <el-select v-model="formModel.inviolableId"
                   placeholder="请选择活动关联权益"
                   filterable
                   remote
                   reserve-keyword
                   clearable
                   :remote-method="(query) => {remoteMethod(query, 'inviolable')}"
                   :loading="loading4"
                   class="w-200"
                   @change="val=>handleSelect(val, 'inviolable')">
          <el-option v-for="item in inviolableFilterList"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <template v-if="formModel.complicationRecommendList.length > 0">
        <el-tabs type="border-card"
                 @tab-click="handleClick"
                 style="width:100%"
                 v-model="tabName">
          <el-tab-pane :label="item.name"
                       v-for="item in tabConTitle"
                       :key="item.id"
                       :name="item.name">
            <el-form-item label="推荐医院检查项目："
                          prop="recommendableProjects"
                          label-width="150px">
              <el-input v-model="formModel.complicationRecommendList[tabIndex].recommendableProjects"
                        placeholder="请输入推荐医院检查项目"
                        class="w-500"
                        :disabled="true"></el-input>
            </el-form-item>

            <!-- 参与活动药品 -->
            <el-form-item label="参与活动药品：">
              <el-table :data="formModel.complicationRecommendList[tabIndex].activityDrugList"
                        style="width: 100%"
                        border
                        tooltip-effect="highLight">
                <el-table-column label="全选"
                                 align="center"
                                 prop="isUp"
                                 width="55">
                  <template slot="header"
                            slot-scope="scope">
                    <el-checkbox v-model="checkAll"
                                 :indeterminate="tableIsIndeterminate"
                                 @change="value=>handleChange(value, 'tableData', formModel.complicationRecommendList[tabIndex].activityDrugList)"></el-checkbox>
                  </template>
                  <template slot-scope="scope">
                    <el-checkbox v-model="scope.row.isUp"
                                 :true-label="1"
                                 :false-label="0"
                                 @change="value =>tableCheckboxChange(scope.row, 'tableData', formModel.complicationRecommendList[tabIndex].activityDrugList)"></el-checkbox>
                  </template>
                </el-table-column>
                <el-table-column prop="factoryName"
                                 label="厂家名称">
                </el-table-column>
                <el-table-column prop="drugType"
                                 label="药品分类"
                                 width="100">
                  <template slot-scope="scope">
                    <el-tag type="success"
                            v-if="scope.row.drugType === 2">化学药</el-tag>
                    <el-tag type="info"
                            v-if="scope.row.drugType === 3">中成药</el-tag>
                    <el-tag type="danger"
                            v-if="scope.row.drugType === 4">保健品</el-tag>
                    <el-tag type="warning"
                            v-if="scope.row.drugType === 5">器械</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="drugName"
                                 label="药品名称">
                </el-table-column>
                <el-table-column prop="standard"
                                 label="规格"
                                 width="100">
                </el-table-column>
                <el-table-column prop="drugPackage"
                                 label="包装"
                                 width="100">
                </el-table-column>
                <el-table-column prop="salesScript"
                                 label="销售导语">
                </el-table-column>
                <el-table-column prop="taboo"
                                 label="禁忌症">
                </el-table-column>
                <el-table-column prop="functionalIndications"
                                 label="功能主治">
                </el-table-column>
                <el-table-column prop="adverseReaction"
                                 label="不良反应">
                </el-table-column>
                <el-table-column prop="isUp"
                                 label="是否为新上架"
                                 width="100"
                                 align="center">
                  <template slot-scope="scope">
                    <el-checkbox v-model="scope.row.isUp"
                                 :true-label="1"
                                 :false-label="0"></el-checkbox>
                  </template>
                </el-table-column>

              </el-table>
            </el-form-item>
            <!-- 联合荐药 -->
            <el-form-item label="联合荐药：">
              <el-button type="primary"
                         @click="handleAdd('medicine')">新 增</el-button>
              <el-table :data="formModel.complicationRecommendList[tabIndex].recommendMedicineRequestDtoListArr"
                        style="width: 100%"
                        border
                        class="mt-20">
                <el-table-column prop="drugType"
                                 label="类别"
                                 width="120">
                  <template slot-scope="scope">
                    <el-tag type="success"
                            v-if="scope.row.drugType === 2">化学药</el-tag>
                    <el-tag type="dager"
                            v-if="scope.row.drugType === 3">中成药</el-tag>
                    <el-tag type="warning"
                            v-if="scope.row.drugType === 4">保健品</el-tag>
                    <el-tag type="info"
                            v-if="scope.row.drugType === 5">器械</el-tag>
                    <el-tag type="dager"
                            v-if="scope.row.drugType === 6">健康筛查</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="value"
                                 label="内容">
                  <template slot-scope="scope">
                    <el-tag type="success"
                            v-for="(item, index) in scope.row.value"
                            :key="index"
                            style="margin-right:5px">
                      {{item.drugName}}--{{item.factoryName}}</el-tag>
                  </template>
                </el-table-column>
              </el-table>
              <table style="width: 100%"
                     border="0"
                     class="table-cell"
                     cellspacing="0"
                     cellpadding="0">
                <tr>
                  <td width="121"
                      class="first-td">
                    <el-tag type="danger">健康筛查项目</el-tag>
                  </td>
                  <td>
                    <el-tag v-for="item in formModel.complicationRecommendList[tabIndex].themeHealthList"
                            :key="item.id"
                            type="danger"
                            style="margin-right:5px">
                      {{item.name}}
                    </el-tag>
                  </td>
                </tr>
                <tr>
                  <td width="121"
                      class="first-td">
                    <el-tag type="info">销售话术</el-tag>
                  </td>
                  <td>
                    {{formModel.complicationRecommendList[tabIndex].recommendSalesScript}}
                  </td>
                </tr>
              </table>
              <medicine-dialog :medicineDataObj="medicineDataObj"
                               @childMedicineData="childMedicineData"
                               :tabIndex=tabIndex
                               :visible.sync="isShowMedicine"
                               v-if="isShowMedicine"></medicine-dialog>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>

      </template>

      <el-form-item label="参与活动客户："
                    class="mt-20"
                    prop="companyId">
        <el-select v-model="formModel.companyId"
                   placeholder="请选择参与活动客户"
                   filterable
                   remote
                   reserve-keyword
                   :remote-method="(query) => {remoteMethod(query, 'activeCustomers')}"
                   :loading="loading5"
                   class="w-200"
                   @change="val=>handleSelect(val, 'activeCustomers')">
          <el-option v-for="item in activeCustomersFilterList"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="参与分店：">
        <el-table :data="tableBranch"
                  border
                  style="width: 100%"
                  @selection-change="handleSelectionChange"
                  ref="asTable"
                  height="460">
          <el-table-column width="50"
                           type="selection"
                           fixed="left">
          </el-table-column>
          <el-table-column prop="id"
                           label="ID">
          </el-table-column>
          <el-table-column prop="hospitalName"
                           label="分店名字">
          </el-table-column>
          <el-table-column prop="manager"
                           label="店长">
          </el-table-column>
          <el-table-column prop="phone"
                           label="联系方式">
          </el-table-column>
        </el-table>
        <p align="left"
           class="mt-20">
          <!-- 已选：{{ allMultipleSelection }} -->
          <el-pagination background
                         @current-change="handleCurrentChange"
                         :current-page.sync="pagination.pageIndex"
                         :page-size="pagination.pageSize"
                         layout="total, prev, pager, next, jumper"
                         :total="pagination.totalNum">
          </el-pagination>
        </p>
      </el-form-item>
      <el-form-item label="活动开始时间："
                    prop="beginTime">
        <el-date-picker v-model="formModel.beginTime"
                        type="date"
                        value-format="timestamp"
                        clearable
                        placeholder="选择活动开始时间"
                        :picker-options="pickerOptionsStart">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="活动结束时间："
                    prop="finishTime">
        <el-date-picker v-model="formModel.finishTime"
                        type="date"
                        value-format="timestamp"
                        clearable
                        placeholder="选择活动结束时间"
                        :picker-options="pickerOptionsEnd">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="解读医院：">
        <el-select v-model="formModel.hospitalId"
                   placeholder="请选择解读医院"
                   filterable
                   remote
                   reserve-keyword
                   :remote-method="(query) => {remoteMethod(query, 'hospital')}"
                   :loading="loading6"
                   class="w-500"
                   @change="val=>handleSelect(val, 'hospital')">
          <el-option v-for="item in interpretationFilterList"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 活动关联知识点 -->
      <el-form-item label="活动关联知识点："
                    label-width="240">
        <el-button type="primary"
                   @click="handleAdd('knowledge')">新 增</el-button>
        <p align="center"
           style="width:100%"
           v-if="knowledgeList.length === 0">
          <el-empty :image-size="100"></el-empty>
        </p>
        <el-card class="mt-20 knowledge-box"
                 v-else>
          <el-timeline>
            <el-timeline-item class="div-list"
                              v-for="(item, index) in knowledgeList"
                              :key="index">
              <span v-html="commonFunction.highLight(item.knowledge, item.keyWord)">{{item.knowledge}}</span>
              <el-button type="danger"
                         :disabled="item.themeId ? true : false"
                         @click="removeRow(knowledgeList, index, 'knowledge')">删 除</el-button>
            </el-timeline-item>
          </el-timeline>
        </el-card>
        <knowledge-dialog :knowledgeDataObj="knowledgeDataObj"
                          @childKnowledgeData="childKnowledgeData"
                          :visible.sync="isShowKnowledge"
                          v-if="isShowKnowledge"></knowledge-dialog>
      </el-form-item>
      <!-- 活动关联重点知识点 -->
      <el-form-item label="活动关联重点知识点："
                    label-width="240">
        <el-button type="primary"
                   @click="handleAdd('goods')">新 增</el-button>
        <p align="center"
           style="width:100%"
           v-if="goodsList.length === 0">
          <el-empty :image-size="100"></el-empty>
        </p>
        <el-card class="mt-20 knowledge-box"
                 v-else>
          <el-timeline>
            <el-timeline-item class="div-list"
                              v-for="(item, index) in goodsList"
                              :key="index">
              <span v-html="commonFunction.highLight(item.knowledge, item.keyWord)">{{item.knowledge}}</span>
              <el-button type="danger"
                         :disabled="item.themeId ? true : false"
                         @click="removeRow(goodsList, index, 'goods')">删 除</el-button>
            </el-timeline-item>
          </el-timeline>
        </el-card>

        <goods-dialog :goodsDataObj="goodsDataObj"
                      @childGoodsData="childGoodsData"
                      :visible.sync="isShowGoods"
                      v-if="isShowGoods"></goods-dialog>
      </el-form-item>
    </el-form>
    <p align="center">
      <el-button type="info"
                 @click="modalClose">取 消</el-button>
      <el-button type="primary"
                 @click="submitForm">新 增</el-button>
    </p>
  </el-dialog>
</template>
<script>
  import { mapGetters } from 'vuex'
  import medicineDialog from './medicineDialog'
  import knowledgeDialog from './knowledgeDialog'
  import goodsDialog from './goodsDialog'
  export default {
    name: 'featureThemeDialog',  // 主题任务发布(专项)
    props: {
      dataObj: {
        type: Object,
        default: {}
      },
      visible: {
        type: Boolean,
        default: false
      },
    },
    data () {
      return {
        title: '新 增',
        loading: false,
        loading2: false,
        loading3: false,
        loading4: false, // 活动关联权益默认false
        loading5: false,
        loading6: false,
        isShowMedicine: false, // 联合荐药
        isShowKnowledge: false, // 知识点
        isShowGoods: false, // 活动商品卖点
        imageUploadUrl: this.api.appUpgradeUpload.url,
        formModel: {
          type: 2,
          themeId: '',
          name: '', // 活动名称
          activityId: null,
          factoryIds: [],
          complicationRecommendList: [
            /*  {
               recommendableProjects: '', // 推荐医院检查项目
               themeHealthDtoList: [], // 已选健康筛查项目列表
               apparatusRequestDtoList: [], // 推荐器械列表
               sellDrugDtoList: [], // 推荐商品列表
               recommendMedicineRequestDtoList: [], // 联合荐药列表
               recommendSalesScript: '', // 销售话术
             } */
          ],
          themeKnowledgeRequestDtoList: [], // 知识点、活动商品卖点
        },
        formRules: {
          themeId: [{ required: true, message: '请选择活动主题', trigger: 'blur' }],
          name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
          factoryIds: [{ required: true, message: '请选择参与活动厂家', trigger: 'blur' }],
          // beginTime: [{ type: 'date', required: true, message: '选择活动开始时间', trigger: ['blur', 'chagne'] }],
          // finishTime: [{ type: 'date', required: true, message: '选择活动结束时间', trigger: ['blur', 'chagne'] }],
          // companyId: [{ required: true, message: '请选择参与活动客户', trigger: 'blur' }],
          // inviolableId: [{ required: true, message: '请选择活动关联权益', trigger: 'blur' }],
        },
        recommendMedicineRequestDtoList: [],
        // 全选标志
        checkAll: false,
        // 半选标志
        tableIsIndeterminate: false,

        medicineDataObj: {}, // 联合荐药
        knowledgeDataObj: {}, // 知识点
        goodsDataObj: {}, // 活动商品卖点
        // 参与活动客户
        activeCustomersList: [],
        activeCustomersFilterList: [],
        // 参与活动客户
        branchList: [],
        branchFilterList: [],
        // 参与分店
        tableBranch: [],

        multipleSelection: [],
        allMultipleSelection: [],
        pagination: {
          pageIndex: 1,
          pageSize: 10
        },
        typeList: [
          { drugType: 2, drugName: "化学药" },
          { drugType: 3, drugName: "中成药" },
          { drugType: 4, drugName: "保健品" },
          { drugType: 5, drugName: "器械" }
        ],
        knowledgeList: [], // 知识点
        goodsList: [], // 活动商品卖点
        inviolableName: '',
        // 活动主题
        activeThemeList: [],
        activeThemeFilterList: [],
        // 活动关联权益
        inviolableList: [],
        inviolableFilterList: [],
        // 解读医院
        interpretationList: [],
        interpretationFilterList: [],
        tabIndex: '0',
        tabConTitle: [], // 根据主题查询合并症,选项卡标题
        tabConData: [], // 选项卡内容
        tabName: '',
        themeId: '',
        pageIndex: 1,
        pageSize: 10,
        // 参与活动厂家
        activityFactory: [],
        activityFilterFactory: [],
        activityId: '',
        activityInviolableId: null,  // 活动权益id
        pickerOptionsStart: {
          disabledDate: time => {
            const endDateVal = new Date(this.formModel.finishTime).getTime()
            if (endDateVal) {
              return time.getTime() > endDateVal - 0
            }
          }
        },
        pickerOptionsEnd: {
          disabledDate: time => {
            const beginDateVal = new Date(this.formModel.beginTime).getTime()
            if (beginDateVal) {
              return time.getTime() < beginDateVal - 0
            }
          }
        }
      }
    },
    methods: {
      modalClose () {
        this.$emit('update:visible', false); // 直接修改父组件的属性
      },
      // 提交
      submitForm () {
        this.$refs.formRef.validate(async (valid) => {
          if (valid) {
            this.formModel.themeKnowledgeRequestDtoList = [...this.knowledgeList, ...this.goodsList];
            this.formModel.hospitalIds = this.allMultipleSelection;
            let activityDrugList = this.formModel.complicationRecommendList[this.tabIndex].activityDrugList;
            if (activityDrugList.length === 0) {
              this.$message.error('请至少选择一个参与活动厂家!');
              return
            }
            let flag = activityDrugList.some(item => {
              if (item.isUp === 1) {
                return true;
              }
            })
            if (!flag) {
              this.$message.error('至少勾选一项参与活动药品!');
              return
            }
            if (this.dataObj) {
              const { data: res } = await this.post(this.api.promote.updateTermActivity, this.formModel, { showFullScreenLoading: true });
              if (res.code === '200') {
                this.$message.success('保存成功!');
                this.modalClose();
                this.$parent.getList();
              }
            } else { // 新增
              const { data: res } = await this.post(this.api.promote.activityTermPublish, this.formModel, { showFullScreenLoading: true });
              if (res.code === '200') {
                this.$message.success('保存成功!');
                this.modalClose();
                this.$parent.getList();
              }
            }
          }
        })
      },
      // 全选或全不选
      handleChange (val, op, table) {
        switch (op) {
          case 'tableData':
            if (val) {
              table.forEach(item => {
                item.isUp = 1;
              });
              this.tableIsIndeterminate = false;
            } else {
              table.forEach(item => {
                item.isUp = 0;
              });
              this.tableIsIndeterminate = false;
            }
            break;
        }

      },
      /**
       * @name: 全选 checkbox部分选择
       * @event: change
       * 1、isAllTrue：checkAll为true，为全选标志，tableIsIndeterminate为false，半选标志不显示
       * 2、isAllFalse：checkAll为false，无标志，tableIsIndeterminate为false，半选标志不显示
       * 3、其他情况，为半选标志
       */

      tableCheckboxChange (val, op, table) {
        switch (op) {
          case 'tableData':
            setTimeout(() => {
              let isAllTrue = table.every(item => item.isUp === 1);
              let isAllFalse = table.every(item => item.isUp === 0);
              if (isAllTrue) {
                this.tableIsIndeterminate = false;
                this.checkAll = true;
              } else if (isAllFalse) {
                this.tableIsIndeterminate = false;
                this.checkAll = false;
              } else {
                this.checkAll = false;
                this.tableIsIndeterminate = true;
              }
            }, 0);
            break;
        }

      },

      handleAdd (option) {
        switch (option) {
          case 'medicine':
            this.isShowMedicine = true;
            let temp = this.formModel.complicationRecommendList[this.tabIndex];
            this.medicineDataObj = {
              themeId: this.formModel.id,
              recommendMedicineRequestDtoList: temp.recommendMedicineRequestDtoList,
              recommendMedicineRequestDtoListArr: temp.recommendMedicineRequestDtoListArr ? temp.recommendMedicineRequestDtoListArr : [],
              recommendSalesScript: temp.recommendSalesScript
            };
            break;
          case 'knowledge':
            this.isShowKnowledge = true;
            break;
          case 'goods':
            this.isShowGoods = true;
            break;
        }
      },
      delRow (table, index, option) {
        switch (option) {
          case 'medicine':
            table.splice(index, 1);
            break;
        }
      },

      setThemeIdFn (data) {
        if (this.dataObj) {
          data['themeId'] = this.dataObj.id;
        } else {
          data['themeId'] = null;
        }
      },
      // 联合荐药,接收子组件传递过来的数据
      childMedicineData (data) {
        this.setThemeIdFn(data);
        this.formModel.complicationRecommendList[this.tabIndex].recommendMedicineRequestDtoList = data.tableData;
        this.formModel.complicationRecommendList[this.tabIndex].recommendMedicineRequestDtoListArr = data.recommendMedicineRequestDtoListArr;
        this.formModel.complicationRecommendList[this.tabIndex].recommendSalesScript = data.recommendSalesScript;
      },
      // 知识点,接收子组件传递过来的数据
      childKnowledgeData (data) {
        this.knowledgeList.push(data);
      },
      // 活动商品卖点,接收子组件传递过来的数据
      childGoodsData (data) {
        this.goodsList.push(data);
      },
      // 删除知识点、活动商品卖点
      removeRow (data, index, option) {
        data.splice(index, 1);
      },
      // 查询分店
      fetchData () {
        this.post(this.api.company.hospitalList, {
          pageIndex: this.pagination.pageIndex - 1,
          pageSize: this.pagination.pageSize,
          searchCondition: '',
          companyId: this.formModel.companyId
        }).then(res => {
          if (res.data.code === '200') {
            setTimeout(_ => {
              this.tableBranch = res.data.object;
              this.pagination.totalNum = res.data.totalNum;
              // 实现分页复选
              setTimeout(_ => {
                this.setSelectedRow();
              }, 50)
            }, 200)
          }
        })
      },
      setSelectedRow () {
        // 设置当前页已选项
        this.tableBranch.forEach(item => {
          if (this.allMultipleSelection.includes(item.hospitalId)) {
            this.$refs.asTable.toggleRowSelection(item, true);
            // console.log(item.id, 'set');
          }
        })
      },
      handleCurrentChange (val) {
        this.pagination.pageIndex = val;
        this.fetchData();
      },

      handleSelectionChange (val) {
        this.multipleSelection = val;
        // 实现分页复选
        setTimeout(_ => {
          this.resolveAllSelection();
        }, 50);
      },
      resolveAllSelection () {
        let currentPageData = this.tableBranch.map(item => item.hospitalId); // 当前页所有数据
        let currentPageSelected = this.multipleSelection.map(item => item.hospitalId); // 当前页已选数据
        let currentPageNotSelected = currentPageData.filter(item => !currentPageSelected.includes(item)); // 当前页未选数据
        // 将当前页已选数据放入所有已选项
        currentPageSelected.forEach(item => {
          if (!this.allMultipleSelection.includes(item)) {
            this.allMultipleSelection.push(item);
          }
        })
        // 将所有已选项数据中当前页没选择的项移除
        currentPageNotSelected.forEach(item => {
          let idx = this.allMultipleSelection.indexOf(item);
          if (idx > -1) {
            this.allMultipleSelection.splice(idx, 1);
          }
        })
      },

      // 远程搜索
      remoteMethod (query, type) {
        if (query !== '') {
          let _this = this;
          if (query) {
            if (type === 'factory') {
              _this.loading2 = true; // 锁住
              this.post(this.api.promote.factoryList, {
                search: query,
                pageIndex: this.pageIndex - 1,
                pageSize: this.pageSize
              }).then(res => {
                if (res.data.code === '200') {
                  _this.loading2 = false;
                  _this.activityFactory = res.data.object;
                }
              })
              setTimeout(() => {
                _this.loading2 = false;
                _this.activityFilterFactory = _this.activityFactory.filter(item => item.name.indexOf(query) > -1);
              }, 200);
            }
            if (type === 'theme') { // 活动主题
              _this.loading3 = true; // 锁住
              this.post(this.api.promote.themeInfoList, {
                search: query,
                type: this.formModel.type,
                pageIndex: this.pageIndex - 1,
                pageSize: this.pageSize
              }).then(res => {
                if (res.data.code === '200') {
                  _this.loading3 = false;
                  _this.activeThemeList = res.data.object;
                }
              })
              setTimeout(() => {
                _this.loading3 = false;
                _this.activeThemeFilterList = _this.activeThemeList.filter(item => item.deviceNames.indexOf(query) > -1);
              }, 200);
            }

            if (type === 'inviolable') { // 活动关联权益
              _this.loading4 = true;
              this.post(this.api.promote.inviolableList, {
                pageIndex: this.pageIndex - 1,
                pageSize: this.pageSize,
                search: query
              }).then(res => {
                if (res.data.code === '200') {
                  _this.loading4 = false;
                  _this.inviolableFilterList = res.data.object;
                  if (_this.activityInviolableId) {
                    let resArr = _this.inviolableFilterList.filter(item => item.name === query);
                    if (resArr.length > 0) {
                      _this.formModel.inviolableId = resArr[0].id;
                    }
                  }
                }
              })
              /*  setTimeout(() => {
                 _this.loading4 = false;
                 _this.inviolableFilterList = _this.inviolableList.filter(item => item.name.indexOf(query) > -1);
               }, 200) */
            }
            if (type === 'activeCustomers') { // 参与活动客户
              _this.loading5 = true;
              this.post(this.api.company.companyList, {
                pageIndex: this.pageIndex - 1,
                pageSize: this.pageSize,
                name: query,
                hospitalType: '',
                status: 1
              }).then(res => {
                if (res.data.code === '200') {
                  _this.loading5 = false;
                  _this.activeCustomersList = res.data.object;
                }
              })
              setTimeout(() => {
                _this.loading5 = false;
                _this.activeCustomersFilterList = _this.activeCustomersList.filter(item => item.name.indexOf(query) > -1);
              }, 200)
            }
            if (type === 'hospital') { // 解读医院
              _this.loading6 = true;
              this.post(this.api.hospitalManager.list, {
                pageIndex: this.pageIndex - 1,
                pageSize: this.pageSize,
                name: query,
              }).then(res => {
                if (res.data.code === '200') {
                  _this.loading6 = false;
                  _this.interpretationList = res.data.object;

                }
              })
              setTimeout(() => {
                _this.loading6 = false;
                _this.interpretationFilterList = _this.interpretationList.filter(item => item.name.indexOf(query) > -1);
              }, 200)
            }
          }



        } else {
          if (type === 'factory') {
            this.activityFilterFactory = [];
          }
          if (type === 'theme') {
            this.activeThemeFilterList = [];
          }
          if (type === 'inviolable') { // 活动关联权益
            this.inviolableFilterList = [];
          }
          if (type === 'activeCustomers') {
            this.activeCustomersFilterList = [];
          }
          if (type === 'hospital') { // 解读医院
            this.interpretationFilterList = [];
          }
        }
      },
      handleSelect (item, type) {
        if (type === 'factory') {
          this.formModel.factoryIds = item;
          this.queryMedicine();
        }
        if (type === 'theme') {
          this.formModel.themeId = item;
          this.post(this.api.promote.themeTermInfo, {
            id: item
          }).then(res => {
            if (res.data.code === '200') {
              let resData = res.data.object;
              this.tabConTitle = resData.complicationInfo.map(item => ({ id: item.id, name: item.name })); // 根据主题查询合并症
              this.tabName = this.tabConTitle[0].name;
              this.formModel.complicationRecommendList = resData.diseaseRecommendInfoList.map(({
                complicationId,
                recommendMedicineRequestDtoList,
                recommendSalesScript,
                recommendableProjects,
                themeHealthDtoList,
                activityDrugList
              }) => ({
                complicationId,
                recommendMedicineRequestDtoList,
                recommendSalesScript,
                recommendableProjects,
                themeHealthList: themeHealthDtoList,
                activityDrugList,
              })); // 根据主题查询合并症

              // return
              resData.diseaseRecommendInfoList[this.tabIndex].recommendMedicineRequestDtoList.forEach(item => {
                item.themeId = resData.id
              })
              const result = this.typeList.map(item => ({
                ...item,
                value: resData.diseaseRecommendInfoList[this.tabIndex].recommendMedicineRequestDtoList.filter(sItem =>
                  item.drugType === sItem.drugType)
              }));
              this.formModel.complicationRecommendList[this.tabIndex].recommendMedicineRequestDtoListArr = result;

              this.knowledgeList = resData.themeKnowledgeRequestDtoList.filter(item => item.type === 1);
              this.goodsList = resData.themeKnowledgeRequestDtoList.filter(item => item.type === 2);
            }
          })
        }

        if (type === 'inviolable') { // 活动关联权益
          this.formModel.inviolableId = item;
        }
        if (type === 'activeCustomers') {
          this.formModel.companyId = item;
          this.allMultipleSelection = [];
          this.fetchData();
        }
        if (type === 'hospital') { // 解读医院
          this.formModel.hospitalId = item;
        }
      },
      // 根据活动主题和参与活动厂家查询参与活动药品
      queryMedicine () {
        if (this.formModel.factoryIds.length === 0) {
          this.$message.error('请至少选择一个参与活动厂家!');
          this.tabConTitle.forEach((item, index) => {
            this.formModel.complicationRecommendList[index].activityDrugList = [];
          })
          return
        }
        this.post(this.api.promote.activitySellDrugList, {
          ids: this.formModel.factoryIds,
          themeId: this.formModel.themeId,
          pageIndex: this.pageIndex - 1,
          pageSize: this.pageSize,
        }).then(res => {
          if (res.data.code === '200') {
            let resData = res.data.object.map(item => ({ ...item, isUp: 1 }));
            if (resData.length > 0) {
              this.tabConTitle.forEach((item, index) => {
                this.$set(this.formModel.complicationRecommendList[index], 'activityDrugList', resData);
              })
            } else {
              this.$message.error('该厂将没有参与活动的药品,不能参加活动!');
              this.formModel.factoryIds = '';
            }
          }
        })
      },
      // 切换Tab
      handleClick (tab, event) {
        this.tabIndex = tab.index;
        // 回显联合荐药列表
        const result = this.typeList.map(item => ({
          ...item,
          value: this.formModel.complicationRecommendList[this.tabIndex].recommendMedicineRequestDtoList.filter(sItem =>
            item.drugType === sItem.drugType)
        }));
        this.formModel.complicationRecommendList[this.tabIndex].recommendMedicineRequestDtoListArr = result;
      },

      // 详情
      async getDetail () {
        const { data: res } = await this.post(this.api.promote.activityTermInfo, { id: this.activityId });
        if (res.code === '200') {
          let resData = res.object;
          // this.formModel = resData;
          this.formModel.type = resData.themeType; // 回显主题类型
          this.formModel.name = resData.name; // 回显活动名称
          this.formModel.activityId = resData.id;
          this.formModel.activityDrugList = resData.activityDrugDtoList; // 回显参加活动药品信息
          this.formModel.themeHealthList = resData.themeHealthDtoList; // 回显已选健康筛查项目
          this.formModel.recommendSalesScript = resData.recommendSalesScript;
          this.formModel.recommendableProjects = resData.recommendableProjects;
          this.formModel.beginTime = resData.beginTime;
          this.formModel.finishTime = resData.finishTime;
          // 回显解读医院
          if (resData.hospitalName) {
            this.formModel.hospitalId = resData.hospitalName.id;
            setTimeout(() => { this.remoteMethod(resData.hospitalName.name, 'hospital'); }, 1000);
          }

          // 回显参与活动客户查询总店
          this.formModel.companyId = resData.companyName.id;
          setTimeout(() => { this.remoteMethod(resData.companyName.name, 'activeCustomers'); }, 1000);
          this.handleSelect(resData.companyName.id, 'activeCustomers'); // 回显分店
          this.allMultipleSelection = resData.hospitalIds; // 回显选中的分店
          this.tableBranch = resData.hospitalDtoList;
          // 回显参与活动厂家
          this.formModel.factoryIds = resData.factoryNames.map(item => item.id);
          resData.factoryNames.forEach((item, index) => {
            setTimeout(() => { this.remoteMethod(item.name, 'factory'); }, index * 1000);
          })
          // 回显活动关联权益
          this.remoteMethod(resData.inviolableInfo.name, 'inviolable');
          this.activityInviolableId = resData.inviolableInfo.id;

          // 回显活动主题
          this.formModel.themeId = resData.themeId;
          // this.remoteMethod(resData.themeName, 'theme');
          this.formModel.activityId = resData.id;

          this.tabConTitle = resData.complicationNames; // 关联病症
          this.formModel.complicationRecommendList = resData.complicationRecommendList; // 回显tab选项卡的内容
          this.tabName = resData.complicationNames[0].name; // 回显tab选项卡第一项选中


          const result = this.typeList.map(item => ({
            ...item,
            value: resData.complicationRecommendList[this.tabIndex].recommendMedicineRequestDtoList.filter(sItem =>
              item.drugType === sItem.drugType)
          }));
          this.formModel.complicationRecommendList[this.tabIndex].recommendMedicineRequestDtoListArr = result;
          this.formModel.complicationRecommendList[this.tabIndex].recommendMedicineRequestDtoList =
            resData.complicationRecommendList[this.tabIndex].recommendMedicineRequestDtoList;

          this.knowledgeList = resData.themeKnowledgeRequestDtoList.filter(item => item.type === 1);
          this.goodsList = resData.themeKnowledgeRequestDtoList.filter(item => item.type === 2);

        }

      }
    },
    created () {
      if (this.dataObj) {
        this.title = '编 辑';
        this.activityId = this.dataObj.id;
        this.getDetail();
      } else {
        this.activityId = null;
      }
    },
    components: {
      'medicine-dialog': medicineDialog,
      'knowledge-dialog': knowledgeDialog,
      'goods-dialog': goodsDialog,
    },
    computed: {
      ...mapGetters(['fileUpload'])
    }
  }
</script>
<style scoped lang="scss">
  .avatar-uploader {
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    /deep/ .el-upload {
      &.el-upload--picture-card {
        width: 98px !important;
        height: 98px !important;
        line-height: 98px !important;
      }
      &:hover {
        border-color: #409eff;
      }
    }
    /deep/ .el-upload-list--picture-card {
      .el-upload-list__item {
        width: 98px;
        height: 98px;
      }
    }
  }
  .knowledge-box {
    width: 100%;
    .el-timeline-item {
      span {
        padding-right: 10px;
        border-right: 1px solid #ebeef5;
        width: calc(100% - 75px);
      }
    }
    /deep/ .el-timeline-item__wrapper {
      top: -10px;
      padding-left: 20px;
      border-bottom: 1px solid #ebeef5;
      .el-timeline-item__content {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .remove {
        font-size: 20px;
        color: #f00;
        cursor: pointer;
      }
    }
  }
  .w-500 {
    width: 500px;
  }
  .table-cell {
    td {
      padding: 3px 10px;
      border-bottom: 1px solid #ebeef5;
      border-right: 1px solid #ebeef5;
      &.first-td {
        border-left: 1px solid #ebeef5;
      }
    }
  }
</style>